package middleware

import (
	"context"
	"errors"
	"fmt"
	"github.com/redis/go-redis/v9"
	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/rest/httpx"
	myerror "insighttracking/common/error"
	"net/http"
)

type AuthMiddleware struct {
	RedisDb *redis.Client
}

func NewAuthMiddleware(redisDb *redis.Client) *AuthMiddleware {
	return &AuthMiddleware{
		RedisDb: redisDb,
	}
}

func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("token")
		fmt.Println("请求的token", token)
		if token == "" {
			//w.WriteHeader(http.StatusAccepted)
			//w.Write([]byte("请登录"))
			httpx.ErrorCtx(r.Context(), w, errors.New("请传递token"))
			return
		}
		redisData, err := m.RedisDb.Get(r.Context(), token).Result()
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, myerror.TokenExpired)
			return
		}
		fmt.Println(redisData, err, "redis中读取的数据")
		accountId := gjson.Get(redisData, "accountId").String()
		username := gjson.Get(redisData, "username").String()
		accountType := gjson.Get(redisData, "accountType").String()
		enterpriseId := gjson.Get(redisData, "enterpriseId").String() // 企业id
		customerId := gjson.Get(redisData, "customerId").String()     // 门店id
		ctx := context.WithValue(r.Context(), "accountId", accountId)
		ctx = context.WithValue(ctx, "username", username)
		ctx = context.WithValue(ctx, "accountType", accountType)
		ctx = context.WithValue(ctx, "enterpriseId", enterpriseId)
		ctx = context.WithValue(ctx, "customerId", customerId)
		next(w, r.WithContext(ctx))
	}
}
